// 位置：OrderController.java
package com.example.demoyyy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.example.demoyyy.JieKouService.OrderServiceJieKou;
import com.example.demoyyy.ShiTiYYY.OrderDetail;
import com.example.demoyyy.ShiTiYYY.Orders;
import com.example.demoyyy.common.BaseContext;
import com.example.demoyyy.common.CustomException;
import com.example.demoyyy.common.R;
import com.example.demoyyy.dto.OrderDto;
import com.example.demoyyy.service.OrderDetailService;
import com.example.demoyyy.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderServiceJieKou orderservicejiekou;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @PostMapping("/submit")
    public void submitorder(@RequestBody Orders orders) {
        log.info("订单数据：{}", orders);
        orderservicejiekou.submit(orders);
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String number, String beginTime, String endTime) {
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Orders::getOrderTime);

        if (StringUtils.isNotBlank(number)) {
            queryWrapper.like(Orders::getNumber, number);
            log.info("订单号：{}", number);
        }

        if (StringUtils.isNotBlank(beginTime) && StringUtils.isNotBlank(endTime)) {
            queryWrapper.between(Orders::getOrderTime, beginTime, endTime);
        }

        orderservicejiekou.page(pageInfo, queryWrapper);
        return R.success(1, "查询成功", pageInfo);
    }

    @PutMapping
    public R<String> updateOrderStatus(
            @RequestParam(value = "id", required = false) Long id,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestBody(required = false) Map<String, Object> requestBody) {

        log.info("更新订单状态：查询参数 - 订单id={}, 状态={}", id, status);
        log.info("更新订单状态：请求体参数 - {}", requestBody);

        Long orderId = null;
        Integer orderStatus = null;

        // 优先使用查询参数
        if (id != null && status != null) {
            orderId = id;
            orderStatus = status;
        }
        // 其次使用请求体参数
        else if (requestBody != null && requestBody.containsKey("id") && requestBody.containsKey("status")) {
            try {
                orderId = Long.valueOf(requestBody.get("id").toString());
                orderStatus = Integer.valueOf(requestBody.get("status").toString());
            } catch (NumberFormatException e) {
                log.error("请求体参数类型转换错误", e);
                return R.error(0, "参数类型错误", null);
            }
        } else {
            log.warn("缺少订单ID或状态参数");
            return R.error(0, "缺少订单ID或状态参数", null);
        }

        try {
            Orders orders = new Orders();
            orders.setId(orderId);
            orders.setStatus(orderStatus);

            boolean result = orderservicejiekou.updateById(orders);
            if (result) {
                log.info("订单状态更新成功：订单id={}, 状态={}", orderId, orderStatus);
                return R.success(1, "订单状态更新成功", null);
            } else {
                log.warn("订单状态更新失败：订单id={}, 状态={}", orderId, orderStatus);
                return R.error(0, "订单状态更新失败", null);
            }
        } catch (Exception e) {
            log.error("更新订单状态异常：订单id={}, 状态={}", orderId, orderStatus, e);
            return R.error(0, "系统异常，请稍后重试", null);
        }
    }

    @GetMapping("/userPage")
    public R<Page<OrderDto>> userPage(int page, int pageSize) {
        // 构造分页构造器对象
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        Page<OrderDto> orderDtoPage = new Page<>();

        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, BaseContext.getCurrentId())
                .orderByDesc(Orders::getOrderTime);

        // 执行分页查询
        orderservicejiekou.page(pageInfo, queryWrapper);

        // 对象拷贝
        BeanUtils.copyProperties(pageInfo, orderDtoPage, "records");
        List<Orders> records = pageInfo.getRecords();

        List<OrderDto> list = records.stream().map((item) -> {
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(item, orderDto);

            // 查询订单详情中的数量信息
            LambdaQueryWrapper<OrderDetail> detailQueryWrapper = new LambdaQueryWrapper<>();
            detailQueryWrapper.eq(OrderDetail::getOrderId, item.getId());
            List<OrderDetail> orderDetails = orderDetailService.list(detailQueryWrapper);

            // 计算总数量
            Integer totalNumber = 0;
            for (OrderDetail detail : orderDetails) {
                if (detail.getNumber() != null) {
                    totalNumber += detail.getNumber();
                }
            }

            // 设置sumNum字段
            orderDto.setSumNum(String.valueOf(totalNumber));
            return orderDto;
        }).collect(Collectors.toList());

        orderDtoPage.setRecords(list);
        return R.success(1, "查询成功", orderDtoPage);
    }



    // 位置：OrderController.java
    @PostMapping("/again")
    public R<String> orderAgain(@RequestBody Map<String, Long> request) {
        Long orderId = request.get("id");
        if (orderId == null) {
            return R.error(0, "订单ID不能为空", null);
        }

        try {
            orderservicejiekou.reorder(orderId);
            return R.success(1, "再来一单成功，已加入购物车", null);
        } catch (CustomException e) {
            return R.error(0, e.getMessage(), null);
        } catch (Exception e) {
            log.error("再来一单失败", e);
            return R.error(0, "系统异常，请稍后重试", null);
        }
    }

}